% Forecasts for quarterly predictions
clear;clc;

load P00Data;
load Market;

h = 1; NW = 1; gam = 5;
for ct = 1:2 % Simple/Log returns
    if ct==1
        RQ = CRSPSP_Q - Rf_Q; RF = Rf_Q; RQ = RQ(3:3:end); RF = RF(3:3:end); MktVar = 3*(MktStd(:,1).^2); MktVar = MktVar(3:3:end);
    else
        RQ = log(1+CRSPSP_Q) - log(1+Rf_Q); RF = log(1+Rf_Q); RQ = RQ(3:3:end); RF = RF(3:3:end); MktVar = 3*(MktStd(:,2).^2); MktVar = MktVar(3:3:end);
    end
    load ResultsFile Results;
    for i = 1:46
        if strcmp(VARS(i).Freq,'Monthly')
            TBeg = find(yyyymm==Results(i).SampleBeg); TEnd = find(yyyymm==Results(i).SampleEnd); OOSBeg = find(yyyymm==Results(i).OOSBeg);
            if i==13 || i==17 % these are PLS variables
                XIS = VARS(i).DataIS{(ct-1)*4+2}; XOOS = VARS(i).DataOOS{(ct-1)*4+2};
            elseif i==22 % svix
                XIS = VARS(i).DataIS{2}; XOOS = VARS(i).DataOOS{2};
            else
                XIS = VARS(i).DataIS; XOOS = VARS(i).DataOOS;
            end
            XIS = XIS(3:3:end); XOOS = XOOS(3:3:end,3:3:end);
            TBeg = ceil(TBeg/3); TEnd = floor(TEnd/3); OOSBeg = ceil(OOSBeg/3);
            XIS = (XIS - mean(XIS(TBeg:TEnd),'omitnan'))/std(XIS(TBeg:TEnd),'omitnan');
        elseif strcmp(VARS(i).Freq,'Quarterly')
            TBeg = find(yyyyq==Results(i).SampleBeg); TEnd = find(yyyyq==Results(i).SampleEnd); OOSBeg = find(yyyyq==Results(i).OOSBeg);
            XIS =  VARS(i).DataIS;
            XOOS = VARS(i).DataOOS;
            XIS = (XIS - mean(XIS(TBeg:TEnd),'omitnan'))/std(XIS(TBeg:TEnd),'omitnan');
        end
        if strcmp(VARS(i).Freq,'Monthly') || strcmp(VARS(i).Freq,'Quarterly')
            Results(i).SampleBeg = yyyyq(TBeg); Results(i).SampleEnd = yyyyq(TEnd); Results(i).OOSBeg = yyyyq(OOSBeg); Results(i).OOSEnd = Results(i).SampleEnd;

            Results(i).ISStats = IS(XIS, RQ, TBeg, TEnd, h, NW);

            [Aols,Aivx,Wivx,WivxInd,Q,corrmat] = ivxlh(RQ(TBeg:TEnd), XIS(TBeg:TEnd), h, 0);
            Results(i).ISStats.KMSSlope = Aivx; Results(i).ISStats.KMSp = Wivx(2);

            Results(i).OOSStats = OOS(XOOS, RQ, RF, MktVar, h, TBeg, TEnd, OOSBeg, gam);
        end % end loop i=1:45
    end
    if ct==1
        Results_Simple_Q = Results;
    else
        Results_Log_Q = Results;
    end
end % end Simple/Log
save ResultsFile Results_* -append;
